import { defineComponent, reactive, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElButton,
  ElTabs,
  ElTabPane,
  ElTable,
  ElTableColumn,
  ElIcon,
  ElSwitch,
  ElMessageBox,
  ElMessage
  // ElNotification
} from 'element-plus'
import {
  Lock,
  Unlock,
  Search,
  // Position,
  Switch,
  SwitchButton,
  Close
} from '@element-plus/icons-vue'
import styles from './index.module.scss'
import websock from '~/utils/socket'

export default defineComponent({
  name: 'RunmapInfo',
  props: ['record', 'close'],
  setup(props: any) {
    const store = useStore()
    const state = reactive<any>({
      tabsName: 1,
      rundataList: [],
      alarmdataList: [],
      command: null,
      onlineStateName: null,
      runStateName: null
    })
    //  关闭
    const handleClose = () => {
      props.close()
    }
    //  工况数据
    const rundata = async () => {
      try {
        const id = props.record.id
        const { data } = await store.dispatch('runmap/HardwareGetRunDataGet', { id })
        state.rundataList = data.loopRunDataList
        if (data.onlineState === 0) {
          state.onlineStateName = '未激活'
        } else if (data.onlineState === 1) {
          state.onlineStateName = '在线'
        } else {
          state.onlineStateName = '离线'
        }
        if (data.runState === 0) {
          state.runStateName = '未激活'
        } else if (data.runState === 1) {
          state.runStateName = '正常'
        } else {
          state.runStateName = '故障'
        }
        store.dispatch('runmap/GetrunStatus', data.runState)
      } catch (error) {}
    }
    //  警报数据
    const alarmdata = async () => {
      const id = props.record.id
      const data: any = await store.dispatch('runmap/HardwareGetRunAlarmDataDataGet', { id })
      state.alarmdataList = data.data
    }
    //  回路开关
    const doStateChange = (value: string | number | boolean, row: any) => {
      const userInfo: any = localStorage.getItem('saber-userInfo')
      const token = JSON.parse(userInfo).accessToken
      const websockParams = {
        deviceId: props.record.id,
        commandId: 'D00034',
        token
      }
      const str = value === 1 ? '打开' : '关闭'
      ElMessageBox.confirm(`确认${str}K${row.loopName}?`, '确认提示', {
        buttonSize: 'small',
        type: 'warning',
        closeOnClickModal: false, // 点遮罩层不关弹窗
        draggable: true // 可拖拽
      })
        .then(async () => {
          websock.send(JSON.stringify(websockParams))
          const params = {
            controlType: value,
            loopName: row.loopName
          }
          handleLockAjax(params)
        })
        .catch(() => {})
    }
    //  全开--1、全关--0
    const handleLock = (value: number) => {
      const userInfo: any = localStorage.getItem('saber-userInfo')
      const token = JSON.parse(userInfo).content.accessToken
      const websockParams = {
        deviceId: props.record.id,
        commandId: 'D00034',
        token
      }
      const str = value === 1 ? '开' : '关'
      ElMessageBox.confirm(`确认全${str}?`, '确认提示', {
        buttonSize: 'small',
        type: 'warning',
        closeOnClickModal: false, // 点遮罩层不关弹窗
        draggable: true // 可拖拽
      })
        .then(async () => {
          websock.send(JSON.stringify(websockParams))
          const params = {
            controlType: value
          }
          handleLockAjax(params)
        })
        .catch(() => {})
    }
    //  开关请求
    const handleLockAjax = async (params: any) => {
      const ajaxParams = {
        deviceId: props.record.id,
        commandId: 'D00034',
        params
      }
      try {
        await store.dispatch('runmap/ExcuteCommandParamPost', ajaxParams)
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
      } catch (error) {}
    }
    //  操作
    const onOperate = async (value: string) => {
      // state![value] = ElNotification({
      //   title: '提示',
      //   type: 'warning',
      //   message: value,
      //   duration: 0
      // })
      // setTimeout(() => {
      //   state![value].close()
      //   state![value] = ElNotification({
      //     title: '提示',
      //     type: 'success',
      //     message: value,
      //     duration: 0
      //   })
      // }, 3000)
      // setTimeout(() => {
      //   state![value].close()
      // }, 6000)

      const ajaxParams = {
        deviceId: props.record.id,
        commandId: state.command![value]
      }
      try {
        await store.dispatch('runmap/ExcuteCommandParamPost', ajaxParams)
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
      } catch (error) {}
    }
    //  获取操作命令
    const commandAjax = async () => {
      const { data } = await store.dispatch('runmap/HardwareGetCommandParam', {
        id: props.record.id
      })
      state.command = data.command
    }

    onMounted(() => {
      commandAjax()
      rundata()
      alarmdata()
    })
    watch(
      () => props.record.id,
      () => {
        commandAjax()
        rundata()
        alarmdata()
      }
    )

    return () => (
      <ElCard
        class={styles['home-info']}
        v-slots={{
          header: () => (
            <div class="card-header">
              <span>
                {props.record.title}&nbsp;&nbsp;
                {state.onlineStateName === '在线' && (
                  <span style="color: rgb(80, 251, 74);">{state.onlineStateName}</span>
                )}
                {state.onlineStateName === '离线' && (
                  <span style="color: rgb(195, 195, 195);">{state.onlineStateName}</span>
                )}
              </span>
              <div class="card-right" onClick={handleClose}>
                <span class="card-right-run">
                  {state.runStateName === '正常' && (
                    <span style="color: rgb(80, 251, 74);">{state.runStateName}</span>
                  )}
                  {state.runStateName === '故障' && (
                    <span style="color: rgb(248, 81, 81);">{state.runStateName}</span>
                  )}
                </span>
                <ElIcon>
                  <Close />
                </ElIcon>
              </div>
              {/* <ElButton class="button" text onClick={handleClose}>
                关闭
              </ElButton> */}
            </div>
          )
        }}
      >
        <div>
          <ElButton onClick={() => handleLock(1)}>
            <ElIcon>
              <Unlock />
            </ElIcon>
            &nbsp;全开
          </ElButton>
          <ElButton onClick={() => handleLock(0)}>
            <ElIcon>
              <Lock />
            </ElIcon>
            &nbsp;全关
          </ElButton>
          <ElButton onClick={() => onOperate('选测')}>
            <ElIcon>
              <Search />
            </ElIcon>
            &nbsp;选测
          </ElButton>
          {/* <ElButton onClick={() => onOperate(2)}>
            <ElIcon>
              <Position />
            </ElIcon>
            &nbsp;发送周设置
          </ElButton> */}
          <ElButton onClick={() => onOperate('复位')}>
            <ElIcon>
              <Switch />
            </ElIcon>
            &nbsp;复位
          </ElButton>
          <ElButton onClick={() => onOperate('重启')}>
            <ElIcon>
              <SwitchButton />
            </ElIcon>
            &nbsp;重启
          </ElButton>
        </div>
        <ElTabs v-model={state.tabsName}>
          <ElTabPane name={1} label="工况数据">
            <ElTable data={state.rundataList} border height={400}>
              <ElTableColumn
                prop="loopName"
                label="开关"
                v-slots={{
                  default: (scope: any) => <span>{`K${scope.row.loopName}`}</span>
                }}
              />
              <ElTableColumn
                prop="diState"
                label="接触器"
                v-slots={{
                  default: (scope: any) => <span>{scope.row.diState === 0 ? '断开' : '闭合'}</span>
                }}
              />
              <ElTableColumn prop="phase" label="线路/相位" width={100} />
              <ElTableColumn prop="voltage" label="电压(V)" />
              <ElTableColumn prop="current" label="电流(A)" />
              <ElTableColumn prop="leakageValue" label="漏电(A)" />
              <ElTableColumn
                label="操作"
                v-slots={{
                  default: (scope: any) => (
                    <ElSwitch
                      v-model={scope.row.doState}
                      active-value={1}
                      inactive-value={0}
                      onChange={(value: any) => doStateChange(value, scope.row)}
                    />
                  )
                }}
              />
            </ElTable>
          </ElTabPane>
          <ElTabPane name={2} label="警报数据">
            <ElTable data={state.alarmdataList} border height={400}>
              <ElTableColumn prop="alarmName" label="发生事件" />
              <ElTableColumn prop="loopName" label="开关" />
              <ElTableColumn prop="loopPhase" label="线路" />
              <ElTableColumn prop="alarmName" label="警报名称" />
              <ElTableColumn
                prop="alarmState"
                label="警报状态"
                v-slots={{
                  default: (scope: any) => (
                    <span>{scope.row.alarmState === 0 ? '恢复' : '报警'}</span>
                  )
                }}
              />
            </ElTable>
          </ElTabPane>
        </ElTabs>
      </ElCard>
    )
  }
})
